package io.github.l86400.component.selenium.core.web.page;

import io.github.l86400.component.selenium.core.web.driver.WebDriver;
import io.github.l86400.component.selenium.core.web.driver.manager.WebDriverManager;
import io.github.l86400.util.bean.EmptyUtil;
import lombok.extern.slf4j.Slf4j;
import org.openqa.selenium.support.ui.WebDriverWait;

import java.time.Duration;

/**
 * @author 86400
 * @since 2021/12/20 9:27
 */
@Slf4j
public abstract class BasePage implements Page {
	protected WebDriverManager webDriverManager;
	protected WebDriver webDriver;
	protected WebDriverWait wait;

	public BasePage(WebDriverManager webDriverManager) {
		this.webDriverManager = webDriverManager;
		this.webDriver = this.webDriverManager.get();
		this.wait = new WebDriverWait(webDriver, Duration.ofSeconds(60));
	}

	public BasePage(WebDriverManager webDriverManager, WebDriver webDriver) {
		this.webDriverManager = webDriverManager;
		if (EmptyUtil.isEmpty(webDriver)) {
			this.webDriver = this.webDriverManager.get();
		} else {
			this.webDriver = webDriver;
		}
		this.wait = new WebDriverWait(webDriver, Duration.ofSeconds(60));
	}

	public void getUrl(String url) {
		if (EmptyUtil.isEmpty(url)) {
			return;
		}
		String currentUrl = webDriver.getCurrentUrl();
		if (EmptyUtil.isEmpty(currentUrl)) {
			webDriver.get(url);
			return;
		}
		if (!currentUrl.equals(url)) {
			webDriver.get(url);
		}
	}

	@Override
	public WebDriver webDriver() {
		return this.webDriver;
	}

	protected boolean titleOrUrlContain(String tital, String url) {
		return titleContain(tital) || urlContain(url);
	}

	protected boolean titleAndUrlContain(String tital, String url) {
		return titleContain(tital) && urlContain(url);
	}

	protected boolean titleContain(String content) {
		return this.webDriver.getTitle().contains(content);
	}

	protected boolean urlContain(String content) {
		return urlContain(content, true);
	}

	protected boolean urlContain(String content, boolean ignoreCase) {
		if (ignoreCase) {
			return this.webDriver.getCurrentUrl().contains(content);
		} else {
			return this.webDriver.getCurrentUrl().contains(content);
		}
	}
}
